package ngames.com.sushitv.action;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import ngames.com.sushitv.R;
import ngames.com.sushitv.action.countrycode.CountryCodeAction;
import ngames.com.sushitv.base.BaseAction;
import ngames.com.sushitv.core.ModelCallback;
import ngames.com.sushitv.tools.LogUtil;
import ngames.com.sushitv.tools.PreferenceManager;

/**
 * Created by Jeffrey on 2016/8/10.
 */
public class SendSmsAction extends BaseAction implements View.OnClickListener {
    private static final int WAIT_TIME_SECOND = 60;
    private EditText mPhoneEdt;
    private EditText mCodesEdt;
    private Button mSendCodesBtn;

    private String mSmsType;
    private String mCountryCode;
    private String mPhoneNum;
    private String mSmsPhone;
    private String mSmsKey;
    private String mSmsCode;
    private int mCurrentSecond;

    CountryCodeAction mCountryCodeAction;

    public SendSmsAction(Activity activity, View baseView) {
        super(activity, baseView);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        View baseView = mBaseView;
        mPhoneEdt = (EditText) baseView.findViewById(R.id.pr_edt_phone);
        mCodesEdt = (EditText) baseView.findViewById(R.id.edt_codes);
        mSendCodesBtn = (Button) baseView.findViewById(R.id.btn_send_codes);
        mSendCodesBtn.setOnClickListener(this);
        continueWait();
        mCountryCodeAction = new CountryCodeAction(mActivity, baseView.findViewById(R.id.base_layout_sms));
        mCountryCodeAction.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mHandler.removeMessages(0);
        saveTime();
        mCountryCodeAction.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mCountryCodeAction.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_send_codes:
                attemptSendSms();
                break;
        }
    }

    private void continueWait() {
        String saveTime = PreferenceManager.getInstance().getSmsTime(mSmsType);
        if (TextUtils.isEmpty(saveTime) || saveTime.indexOf("@") < 0) {
            return;
        }
        String[] timeArray = saveTime.split("@");
        long sysTime = Long.parseLong(timeArray[0]);
        int time = Integer.parseInt(timeArray[1]);
        int currentSecond = (int) (time - (System.currentTimeMillis() - sysTime) / 1000);
        if (currentSecond < WAIT_TIME_SECOND) {
            waitTimeSend(++currentSecond);
        }
    }

    private void saveTime() {
        if (mCurrentSecond > 0 && mCurrentSecond < WAIT_TIME_SECOND) {
            String time = System.currentTimeMillis() + "@" + mCurrentSecond;
            LogUtil.d("SendSmsAction", "saveTime() time = " + time);
            PreferenceManager.getInstance().saveSmsTime(mSmsType, time);
        } else {
            PreferenceManager.getInstance().saveSmsTime(mSmsType, null);
        }
    }

    private void waitTimeSend(int currentSecond) {
        mSendCodesBtn.setEnabled(false);
        mCurrentSecond = currentSecond;
        mHandler.removeMessages(0);
        mHandler.sendEmptyMessage(0);
    }

    private void attemptSendSms() {
        mPhoneEdt.setError(null);
        String phoneNumber = mPhoneEdt.getText().toString();
        String countryCode = mCountryCodeAction.getCountryCode();

        boolean cancel = false;
        View focusView = null;

        if (TextUtils.isEmpty(phoneNumber)) {
            mPhoneEdt.setError("input phone");
            focusView = mPhoneEdt;
            cancel = true;
        }
        if (cancel) {
            focusView.requestFocus();
        } else {
            sendSms(countryCode + phoneNumber);
        }
    }

    private void sendSms(final String phone) {
        mSmsKey = null;
        mSmsPhone = null;
        waitTimeSend(WAIT_TIME_SECOND);
        getAppModel().getUserService().sendSms(mSmsType, phone, new ModelCallback<String>() {
            @Override
            public void onBeforeRequest(String urlTag) {

            }

            @Override
            public void onSuccess(String data) {
                mSmsKey = data;
                mSmsPhone = phone;
            }

            @Override
            public void onFailure(String errorEvent, String message) {

            }
        });
    }

    public boolean checkForRegister() {
        mPhoneEdt.setError(null);
        mCodesEdt.setError(null);

        mCountryCode = mCountryCodeAction.getCountryCode();
        mPhoneNum = mPhoneEdt.getText().toString();
        mSmsCode = mCodesEdt.getText().toString();
        boolean cancel = false;
        View focusView = null;

        if (TextUtils.isEmpty(mCountryCode)) {

        } else if (TextUtils.isEmpty(mPhoneNum)) {
            mPhoneEdt.setError("Enter phone number");
            focusView = mPhoneEdt;
            cancel = true;
        } else if (TextUtils.isEmpty(mSmsKey)) {
            mCodesEdt.setError("get codes");
            focusView = mCodesEdt;
            cancel = true;
        } else if (TextUtils.isEmpty(mSmsCode)) {
            mCodesEdt.setError("input codes");
            focusView = mCodesEdt;
            cancel = true;
        } else if (!mSmsPhone.equals(mCountryCode + mPhoneNum)) {
            mCodesEdt.setError("get codes");
            focusView = mCodesEdt;
            cancel = true;
        }
        if (cancel) {
            focusView.requestFocus();
        }
        return cancel;
    }

    public void setSmsType(String smsType) {
        mSmsType = smsType;
    }

    public String getCountryCode() {
        return mCountryCode;
    }

    public String getPhoneNum() {
        return mPhoneNum;
    }

    public String getSmsKey() {
        return mSmsKey;
    }

    public String getSmsCode() {
        return mSmsCode;
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    int currentSecond = --mCurrentSecond;
                    mSendCodesBtn.setText(getString(R.string.text_wait_send_sms, currentSecond));
                    if (currentSecond > 0) {
                        mHandler.sendEmptyMessageDelayed(0, 1000);
                    } else {
                        mSendCodesBtn.setEnabled(true);
                        mSendCodesBtn.setText(R.string.text_send_sms);
                    }
                    break;
            }
        }
    };
}
